package high.concurrent.pay.factory;

import com.alibaba.fastjson.JSONObject;
import high.concurrent.enums.BizCodeEnum;
import high.concurrent.enums.PayTypeEnum;
import high.concurrent.exception.BizException;
import high.concurrent.pay.service.impl.AliPayServiceImpl;
import high.concurrent.pay.service.impl.JDPayServiceImpl;
import high.concurrent.pay.service.impl.WechatPayServiceImpl;
import high.concurrent.pay.strategypattern.payCreate.PayContext;
import high.concurrent.vo.PayInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 支付的简单工厂模式
 */
@Component
@Slf4j
public class PayFactory {

    /**
     * 创建订单
     * @param payInfoVO
     * @return
     */
    public String createOrder(PayInfoVO payInfoVO){
        CloseableHttpResponse closeableHttpResponse = null;
        String qrCode = "";
        // 判断支付方式
        if(PayTypeEnum.WECHAT.name().equalsIgnoreCase(payInfoVO.getPayType())){

            // 微信支付
            PayContext payContext = new PayContext(new WechatPayServiceImpl());
            closeableHttpResponse = payContext.createOrder(payInfoVO);
        }else if(PayTypeEnum.ALIPAY.name().equalsIgnoreCase(payInfoVO.getPayType())){

            // 支付宝支付
            PayContext payContext = new PayContext(new AliPayServiceImpl());
            closeableHttpResponse = payContext.createOrder(payInfoVO);
        }else if(PayTypeEnum.JDPAY.name().equalsIgnoreCase(payInfoVO.getPayType())){

            // 京东支付
            PayContext payContext = new PayContext(new JDPayServiceImpl());
            closeableHttpResponse = payContext.createOrder(payInfoVO);
        }
        // 解析返回的对象
        JSONObject jsonObject = this.closeableHttpResponse(closeableHttpResponse);
        qrCode = (String) jsonObject.get("code_url");
        return qrCode;
    }

    /**
     * 解析响应体
     * @param closeableHttpResponse
     * @return
     */
    private JSONObject closeableHttpResponse(CloseableHttpResponse closeableHttpResponse){
        // 响应码
        int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
        // 响应体
        String responseBody = null;
        try {
            responseBody = EntityUtils.toString(closeableHttpResponse.getEntity());
        } catch (IOException e) {
            log.error("解析相应错误： {}", closeableHttpResponse);

        }
        log.info("响应码: {}, 响应体: {}", statusCode, responseBody);
        if(statusCode == 200){
            return JSONObject.parseObject(responseBody);
        }else{
            throw new BizException(BizCodeEnum.JIEXI_DEFAIL);
        }
    }
}
